using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Read.Controllers
{
    /// <summary>
    /// 轮播图控制器
    /// 提供轮播图相关的查询接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class CarouselController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<CarouselController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public CarouselController(IMediator mediator, ILogger<CarouselController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 获取轮播图列表
        /// </summary>
        /// <param name="title">标题关键词（可选）</param>
        /// <param name="status">状态（可选）</param>
        /// <param name="startTime">开始时间（可选）</param>
        /// <param name="endTime">结束时间（可选）</param>
        /// <param name="currentPage">当前页码（可选，默认为1）</param>
        /// <param name="pageSize">每页数量（可选，默认为10）</param>
        /// <returns>轮播图列表</returns>
        [HttpGet]
        [ProducesResponseType(typeof(APIResult<PageResponse<CarouselDto>>), 200)]
        public async Task<ActionResult<APIResult<PageResponse<CarouselDto>>>> GetCarousels(
            [FromQuery] string? title = null,
            [FromQuery] S.M.SmartMedical.Domain.Enums.CarouselStatus? status = null,
            [FromQuery] DateTime? startTime = null,
            [FromQuery] DateTime? endTime = null,
            [FromQuery] int currentPage = 1,
            [FromQuery] int pageSize = 10)
        {
            try
            {
                _logger.LogInformation("接收到获取轮播图列表请求，标题关键词：{Title}，状态：{Status}", title, status);

                var query = new GetCarouselsQuery
                {
                    Title = title,
                    Status = status,
                    StartTime = startTime,
                    EndTime = endTime,
                    CurrentPage = currentPage,
                    PageSize = pageSize
                };

                var result = await _mediator.Send(query);

                _logger.LogInformation("成功处理获取轮播图列表请求，返回 {Count} 个轮播图", result.Data?.Items?.Count ?? 0);

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理获取轮播图列表请求时发生错误");
                return StatusCode(500, new APIResult<PageResponse<CarouselDto>>
                {
                    Code = APIEnum.Fail,
                    Message = "服务器内部错误，请稍后重试",
                    Data = new PageResponse<CarouselDto>()
                });
            }
        }

        /// <summary>
        /// 获取轮播图详情
        /// </summary>
        /// <param name="id">轮播图ID</param>
        /// <returns>轮播图详情</returns>
        [HttpGet("{id}")]
        [ProducesResponseType(typeof(APIResult<CarouselDto>), 200)]
        public async Task<ActionResult<APIResult<CarouselDto>>> GetCarouselDetail(long id)
        {
            try
            {
                _logger.LogInformation("接收到获取轮播图详情请求，ID：{Id}", id);

                var query = new GetCarouselDetailQuery(id);
                var result = await _mediator.Send(query);

                _logger.LogInformation("获取轮播图详情请求处理完成，ID：{Id}，结果：{Code}",
                    id, result.Code);

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取轮播图详情接口异常，ID：{Id}", id);
                return StatusCode(500, new APIResult<CarouselDto>
                {
                    Code = APIEnum.Fail,
                    Message = "获取轮播图详情失败，系统异常",
                    Data = null!
                });
            }
        }
    }
}